<?php

namespace src\models;

use PDO;

class Notice
{
    private $pdo;

    public function __construct($pdo)
    {
        $this->pdo = $pdo;
    }

    public function getAll()
    {

        return $this->pdo->query("SELECT * FROM notices ORDER BY created_at DESC");
    }

//    通过ID获取公告
    public function getNoticeById($id)
    {
        $stmt = $this->pdo->prepare("SELECT * FROM notices WHERE id = :id", [':id' => $id]);
        $stmt->execute(['id' => $id]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    }

    //创建一个新公告
    public function create($title, $content, $authorId)
    {
        $stmt =$this->pdo->prepare("INSERT INTO notices (title, content, author_id) VALUES (:title, :content, :author_id)");
        return $stmt->execute([
            'title' => $title,
            'content' => $content,
            'author_id' => $authorId
        ]);
    }



//    编辑公告
    public function editNotice($id, $title, $content)
    {
        $stmt = $this->pdo->prepare("UPDATE notices SET title = :title, content = :content WHERE id = :id");
        return $stmt->execute([
            'title' => $title,
            'content' => $content,
            'id' => $id
        ]);
    }

//    删除公告
    public function deleteNotice($id)
    {
        $stmt = $this->pdo->prepare("DELETE FROM notices WHERE id = :id", [':id' => $id]);
        return $stmt->execute(['id' => $id]);
    }
}